package com.xiaoran.springbt02web.conver;

import com.xiaoran.springbt02web.bean.Persion;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import javax.swing.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
//自定义的convert
public class XiaoranMessageConverter implements HttpMessageConverter<Persion> {

    @Override//能不能把clazz读成mediaType
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }

    @Override//能不能读,clazz 返回值类型
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        //只要我们返回的类型是persion我们就可以读
        return clazz.isAssignableFrom(Persion.class);
    }

    @Override//获取所有内容的类型
    //服务器要统计所有MessageConverter都能写出哪些内容类型
    //我们这里就可以告诉我们的springboot我们的自定义数据类型 是什么

    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/x-xiaoran");
    }

    @Override
    public Persion read(Class<? extends Persion> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(Persion persion, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //自定义协议的写出
        String data=persion.getUsername()+";"+persion.getAge()+";"+persion.getBirth();
        //写出来
        OutputStream body=outputMessage.getBody();
        body.write( data.getBytes());
    }
}
